package com.pansoft.openplanet.activity;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.efounder.chat.model.LogoutEvent;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.tbs.Md5Tool;
import com.efounder.util.ToastUtil;
import com.efounder.utils.EasyPermissionUtils;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.Contact;
import com.pansoft.openplanet.util.LoginFlowManager;
import com.pansoft.openplanet.util.TCRequestUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import pub.devrel.easypermissions.AfterPermissionGranted;

/**
 * 导入粉丝
 * Created by will on 18-3-20.
 */

public class ImportFansActivity extends TCBaseActivity implements View.OnClickListener {

    private String TAG = this.getClass().getSimpleName();
    private String number;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.talk_chain_activity_import_contacts);
        setEnableScreenShotListen(false);
        number = getIntent().getExtras().getString("number");
        //  String number = "110";
        ImageView ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(R.string.openplanet_title_import_fans);
        TextView tvSkip = (TextView) findViewById(R.id.tv_save);
        tvSkip.setVisibility(View.VISIBLE);
        tvSkip.setText(R.string.common_text_skip);
        if (getIntent().hasExtra("hasRightButton")) {
            tvSkip.setVisibility(View.GONE);
        } else {
            //进入导入粉丝流程
            EnvironmentVariable.setProperty(LoginFlowManager.getIsImportFansKey(number), "true");


        }

        tvSkip.setOnClickListener(this);
        TextView tvPhone = (TextView) findViewById(R.id.tv_phone);
        tvPhone.setText(number);
        Button tvImport = (Button) findViewById(R.id.tv_import);
        tvImport.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.tv_import) {
            checkMyPermission();
        } else if (id == R.id.tv_save) {//跳过
            gotoNextPage();
            //完成导入粉丝流程
            EnvironmentVariable.setProperty(LoginFlowManager.getIsImportFansKey(number), "false");
            //完成注册流程
            EnvironmentVariable.setProperty(LoginFlowManager.getIsRegisterKey(number), "false");
        }
    }

    @AfterPermissionGranted(EasyPermissionUtils.PERMISSION_CODE_READ_CONTACT)
    private void checkMyPermission() {
        if (EasyPermissionUtils.checkReadContactPermission() ) {
            loadContact();
        }else{
            EasyPermissionUtils.requestReadContactPermission(this);
        }
    }

    private void loadContact() {
        Disposable disposable = Observable.create(new ObservableOnSubscribe<List<Contact>>() {
            @Override
            public void subscribe(ObservableEmitter<List<Contact>> emitter) throws Exception {
                List<Contact> contacts = getContacts();
                emitter.onNext(contacts);
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .map(new Function<List<Contact>, String>() {
                    @Override
                    public String apply(@NonNull List<Contact> contacts) throws Exception {
                        if (contacts != null && contacts.size() == 0) {
                            return "";
                        }
                        JSONArray jsonArray = new JSONArray();
                        for (Contact contact : contacts) {
                            for (Contact.Phone phone : contact.getPhones()) {
                                JSONObject jsonObject1 = new JSONObject();
                                jsonObject1.put("unionId", contact.getId());
                                if (contact.getName() == null || "".equals(contact.getName())) {
                                    jsonObject1.put("linkManUserName", "未知用户");
                                } else {
                                    jsonObject1.put("linkManUserName", contact.getName());
                                }

                                if (phone.getPhone() != null) {
                                    jsonObject1.put("linkManIdMd5", Md5Tool.hashKey(phone.getPhone()).toUpperCase());
                                } else {
                                    jsonObject1.put("linkManIdMd5", "");
                                }

                                jsonObject1.put("phoneTitle", phone.getType());
                                jsonArray.put(jsonObject1);
                            }
                        }
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("linkMans", jsonArray);
                        return jsonObject.toString();
                    }
                }).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showLoading(ResStringUtil.getString(R.string.open_planet_importing));
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String json) throws Exception {
                        //  Log.i("tag", json);

                        if ("".equals(json)) {
                            gotoNextPage();
                            return;
                        }
                        upLoadServer(json);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissLoading();
                        ToastUtil.showToast(getApplicationContext(), R.string.common_text_import_fail);
                        gotoNextPage();
                    }
                });


        addDisposable(disposable);
    }

    private void upLoadServer(String jsonString) {
        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", EnvironmentVariable.getProperty("tc_access_token"));
        params.put("linkMans", jsonString);
        TCRequestUtil.postOAuthRequest(TAG, "linkMan/upLoadLinkMans", params, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.has("result") && jsonObject.getString("result").equals("success")) {
                        ToastUtil.showToast(getApplicationContext(), R.string.common_text_import_success);
                        //完成导入粉丝流程
                        EnvironmentVariable.setProperty(LoginFlowManager.getIsImportFansKey(number), "false");
                        //完成注册流程
                        EnvironmentVariable.setProperty(LoginFlowManager.getIsRegisterKey(number), "false");

                        gotoNextPage();

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    ToastUtil.showToast(getApplicationContext(), R.string.common_text_import_fail);
                    gotoNextPage();
                }
            }

            @Override
            public void onFail(String error) {
                dismissLoading();
                if (error != null && error.equals("TokenExpireLogOut")) {
                    //showLogOutAlert();
                    EventBus.getDefault().post(new LogoutEvent(LogoutEvent.TYPE_LOGIN_OUT_OF_DATE));
                    return;
                }

                gotoNextPage();
                ToastUtil.showToast(getApplicationContext(), R.string.common_text_import_fail);

            }
        });
    }

    private void gotoNextPage() {
        Intent intent = new Intent(ImportFansActivity.this, TabBottomActivityForTalkChain.class);
        intent.putExtra("unDoCheck", "true");//从登录界面跳转无需再次检查是否升级
        startActivity(intent);
        ActivityCompat.finishAffinity(ImportFansActivity.this);
    }

    private List<Contact> getContacts() {
        List<Contact> contacts = new ArrayList<>();
        Uri uri = Uri.parse("content://com.android.contacts/contacts");
        ContentResolver resolver = this.getContentResolver();
        Cursor cursor = resolver.query(uri, new String[]{"_id"}, null, null, null);
        contacts.clear();
        while (cursor.moveToNext()) {
            int contactsId = cursor.getInt(0);
            Contact contact = new Contact();
            List<Contact.Phone> phones = new ArrayList<>();
            StringBuilder builder = new StringBuilder("contactsId=");
            builder.append(contactsId);
            uri = Uri.parse("content://com.android.contacts/contacts/" + contactsId + "/data");
            Cursor dataCursor = resolver.query(uri, new String[]{"mimetype", "data1", "data2", "data15"}, null, null, null);
            if (dataCursor == null) {
                continue;
            }

            while (dataCursor.moveToNext()) {

                String data = dataCursor.getString(dataCursor.getColumnIndex("data1"));
                if (data != null) {
                    data = data.replace(" ", "");
                }
                String phoneType = dataCursor.getString(dataCursor.getColumnIndex("data2"));
                byte[] bytes = dataCursor.getBlob(dataCursor.getColumnIndex("data15"));
                if (bytes != null) {
                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                }
                String type = dataCursor.getString(dataCursor.getColumnIndex("mimetype"));
                if ("vnd.android.cursor.item/name".equals(type)) {
                    contact.setName(data);
                    contact.setId(String.valueOf(contactsId));
                    builder.append(", name=" + data);
                } else if ("vnd.android.cursor.item/phone_v2".equals(type)) {
                    Contact.Phone phone = contact.new Phone();
                    phone.setPhone(data);
                    if ("1".equals(phoneType)) {
                        phone.setType("住宅");
                    } else if ("2".equals(phoneType)) {
                        phone.setType("手机");
                    } else if ("3".equals(phoneType)) {
                        phone.setType("单位");
                    } else {
                        phone.setType("其他");
                    }

                    builder.append(", phone=" + data);
                    builder.append(",phoneType=" + phoneType);
                    phones.add(phone);
                }
                contact.setPhones(phones);

            }
            dataCursor.close();
            Log.d("IMPORTCONTACTS", builder.toString());
            contacts.add(contact);
        }
        cursor.close();
        return contacts;

    }

//    private void showLogOutAlert() {
//        new AlertDialog.Builder(this)
//                .setTitle(R.string.common_text_hint)
//                .setMessage("用户登录过期，请重新登录")
//                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//                        EventBus.getDefault().post(new LogoutEvent());
//                    }
//                })
//                .setCancelable(false)
//                .create().show();
//    }

    @Override
    protected void onStop() {
        super.onStop();
       // EFHttpRequest.cancelRequest(TAG);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dispose();
    }
}
